
//标准输入输出函数头文件
#include <stdio.h>
//字符串操作函数头文件
#include <string.h>

#include <unistd.h>
//文件操作函数头文件
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
//
#include <termios.h>

#include <errno.h>

#define MAX_SIZE 1000

int set_opt(int,int,int,char,int);

void main()
{
	int fd_uart,fd_file,nByte;
	//(1)串口3和文件的地址，注意ttySAC3是con2，靠近耳机接口的串口
	char *uart3 = "/dev/ttySAC3";
	char *IOtest = "";

	char *uart_out = "hello\n";
	char buffer_read[MAX_SIZE];
	//下面两句用于测试sprintf函数
	sprintf(buffer_read, "test sprintf func: I married %s in %d\n", "FenTimo", 2020);
	printf(buffer_read);

	//(2)打开串口3，路径名指向指向终端设备
	if((fd_uart = open(uart3, O_RDWR|O_NOCTTY|O_NDELAY))<0)
		printf("open %s is failed",uart3);
	else{
		//(3)初始化串口3，波特率9600,8位数据位，无校验，1位停止位
		set_opt(fd_uart,115200,8,'N',1);
		while(1){
			//(4)将uart_out字符串通过串口发送出去
			tcflush(fd_uart,TCIOFLUSH);
			write(fd_uart,uart_out,6);
            write(fd_uart,"hello\n",6);
		}
	}
}

/************************************
* 函数：串口初始化函数
* 参数：
	fd:打开串口返回的句柄
	nSpeed：波特率
	nBits：数据位
	nEvent：奇偶校验 "o"奇校验 "E"偶校验 "N" 无校验
	nStop：停止位
*返回值： return 0
***********************************/
int set_opt(int fd_uart,int nSpeed, int nBits, char nEvent, int nStop)
{
	struct termios newtio,oldtio;
	if  ( tcgetattr( fd_uart,&oldtio)  !=  0) {
		perror("SetupSerial 1");
		return -1;
	}
	bzero( &newtio, sizeof( newtio ) );
	newtio.c_cflag  |=  CLOCAL | CREAD;
	newtio.c_cflag &= ~CSIZE;

	switch( nBits )
	{
		case 7:
			newtio.c_cflag |= CS7;
			break;
		case 8:
			newtio.c_cflag |= CS8;
			break;
	}

	switch( nEvent )
	{
	case 'O':
		newtio.c_cflag |= PARENB;
		newtio.c_cflag |= PARODD;
		newtio.c_iflag |= (INPCK | ISTRIP);
		break;
	case 'E':
		newtio.c_iflag |= (INPCK | ISTRIP);
		newtio.c_cflag |= PARENB;
		newtio.c_cflag &= ~PARODD;
		break;
	case 'N':
		newtio.c_cflag &= ~PARENB;
		break;
	}

	switch( nSpeed )
	{
		case 2400:
			cfsetispeed(&newtio, B2400);
			cfsetospeed(&newtio, B2400);
			break;
		case 4800:
			cfsetispeed(&newtio, B4800);
			cfsetospeed(&newtio, B4800);
			break;
		case 9600:
			cfsetispeed(&newtio, B9600);
			cfsetospeed(&newtio, B9600);
			break;
		case 115200:
			cfsetispeed(&newtio, B115200);
			cfsetospeed(&newtio, B115200);
			break;
		case 460800:
			cfsetispeed(&newtio, B460800);
			cfsetospeed(&newtio, B460800);
			break;
		default:
			cfsetispeed(&newtio, B9600);
			cfsetospeed(&newtio, B9600);
			break;
	}
	if( nStop == 1 )
		newtio.c_cflag &=  ~CSTOPB;
	else if ( nStop == 2 )
		newtio.c_cflag |=  CSTOPB;
		newtio.c_cc[VTIME]  = 0;
		newtio.c_cc[VMIN] = 0;
		tcflush(fd_uart,TCIFLUSH);
	if((tcsetattr(fd_uart,TCSANOW,&newtio))!=0)
	{
		perror("com set error");
		return -1;
	}

	//	printf("set done!\n\r");
	return 0;
}


